//
//  PlayerVideoViewController.m
//  网易公开课项目
//
//  Created by 林 艺 on 13-11-14.
//  Copyright (c) 2013年 Marklin. All rights reserved.
//

#import "PlayerVideoViewController.h"
#import "LoadCourseDataManager.h"

@interface PlayerVideoViewController ()

@end

@implementation PlayerVideoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil withPlayType:(PlayType)playFlag

{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _playFlag = playFlag;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.wantsFullScreenLayout = YES;
    self.loadingAIV.hidesWhenStopped = YES;
    self.topLabel.text = [NSString stringWithFormat:@"第%@课 %@", self.videoModel.pnumber, self.videoModel.title];
    self.middleTitleLabel.text = [NSString stringWithFormat:@"第%@课 %@", self.videoModel.pnumber, self.videoModel.title];
    NSLog(@"playFlag >>> %d", _playFlag);
    if (_playFlag == PlayWithURL)
    {
        [self playVideoWithUrl];
    }
    else
    {
        [self playVideoWithLocal];
    }
    
}

- (void)playVideoWithLocal
{
    _myMovie = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:self.videoModel.localPlayPath]];
    NSLog(@"localPlayPath >> %@", self.videoModel.localPlayPath);
    _myPlayer = [AVPlayer playerWithPlayerItem:_myMovie];
    
    AVPlayerLayer *layer = (AVPlayerLayer *)self.playView.layer;
    [layer setPlayer:_myPlayer];
    CMTime movieTime = _myMovie.asset.duration;
    NSInteger movieSeconds = CMTimeGetSeconds(movieTime);
    
//    CMTime movieTime = _myMovie.duration;
//    NSLog(@"%lld", movieTime.value);
//    NSInteger movieSeconds = movieTime.value/movieTime.timescale;
    
    self.playProgressSlider.maximumValue = movieSeconds;
    self.rightLabel.text = [NSString stringWithFormat:@"%02d:%02d", movieSeconds/60, movieSeconds%60];
    
    [_timer invalidate];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(refreshSlider) userInfo:nil repeats:YES];
    _barTimer = [NSTimer scheduledTimerWithTimeInterval:7 target:self selector:@selector(barHideTwoSecond) userInfo:nil repeats:NO];
    
    self.playView.hidden = NO;
    self.backView.hidden = YES;
    [_myPlayer play];

}

- (void)playVideoWithUrl
{
    [self.loadingAIV startAnimating];

    dispatch_queue_t rootQueue;
    rootQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(rootQueue, ^{
        _myMovie = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.videoModel.repovideourl]];
        
        _myPlayer = [AVPlayer playerWithPlayerItem:_myMovie];
        
        AVPlayerLayer *layer = (AVPlayerLayer *)self.playView.layer;
        [layer setPlayer:_myPlayer];
        
        CMTime movieTime = _myMovie.asset.duration;
//        NSLog(@"%lld", movieTime.value);
        NSInteger movieSeconds = movieTime.value/movieTime.timescale;
        [_myPlayer play];
        CMTime sTime = _myMovie.asset.duration;
        sTime.value = self.videoModel.lastPlayTime*sTime.timescale;
        [_myPlayer seekToTime:sTime];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.playProgressSlider.maximumValue = movieSeconds;
            
            self.rightLabel.text = [NSString stringWithFormat:@"%02d:%02d", movieSeconds/60, movieSeconds%60];
            
            [_timer invalidate];
            _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(refreshSlider) userInfo:nil repeats:YES];
            _barTimer = [NSTimer scheduledTimerWithTimeInterval:7 target:self selector:@selector(barHideTwoSecond) userInfo:nil repeats:NO];
            
            self.playView.hidden = NO;
            self.backView.hidden = YES;
            [self.loadingAIV stopAnimating];
        });
    });

}


- (void)refreshSlider
{
    CMTime curTime = _myMovie.currentTime;//返回当前时间类型
//     NSInteger movieSeconds = CMTimeGetSeconds(movieTime);
    self.playProgressSlider.value = curTime.value/curTime.timescale;
    NSLog(@"progressSlider >> %f", self.playProgressSlider.value);
    NSLog(@"value >>>> %lld", curTime.value);
    //设置当前时间
    NSInteger movieSeconds = curTime.value/curTime.timescale;
    NSLog(@">>>%d", movieSeconds);
    _leftLabel.text = [NSString stringWithFormat:@"%02d:%02d", movieSeconds/60, movieSeconds%60];
    
}

- (void)barHideTwoSecond
{
    [[UIApplication sharedApplication]setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    [UIView animateWithDuration:0.3 animations:^{
        self.topView.hidden = YES;
        self.controlView.alpha = 0;
    }];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --
#pragma mark 播放按键

- (IBAction)playButtonClicked:(UIButton *)sender
{
    if ([_timer isValid])
    {
        [_timer invalidate];
        _timer = nil;
        [_myPlayer pause];
        [sender setImage:[UIImage imageNamed:@"play_ico.png"] forState:UIControlStateNormal];
        [sender setImage:[UIImage imageNamed:@"play_ico_active.png"] forState:UIControlStateHighlighted];
    }
    else
    {
        [_timer invalidate];
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(refreshSlider) userInfo:nil repeats:YES];
        [_myPlayer play];
        [sender setImage:[UIImage imageNamed:@"pause_ico.png"] forState:UIControlStateNormal];
        [sender setImage:[UIImage imageNamed:@"pause_ico_active.png"] forState:UIControlStateHighlighted];
    }
}

- (IBAction)playProgressSlid:(UISlider *)sender
{
    [_myPlayer pause];
    [_barTimer invalidate];
    _barTimer = nil;
    [_timer invalidate];
    _timer = nil;
    CMTime sTime = _myMovie.asset.duration;
    sTime.value = sender.value*sTime.timescale;
    
    NSInteger movieSeconds = sTime.value/sTime.timescale;
    _leftLabel.text = [NSString stringWithFormat:@"%02d:%02d", movieSeconds/60, movieSeconds%60];
    
    [_myPlayer seekToTime:sTime];
    [_myPlayer play];
    [_timer invalidate];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(refreshSlider) userInfo:nil repeats:YES];
    [self.playButton setImage:[UIImage imageNamed:@"pause_ico.png"] forState:UIControlStateNormal];
    [self.playButton setImage:[UIImage imageNamed:@"pause_ico_active.png"] forState:UIControlStateHighlighted];
}

- (IBAction)backButtonClicked:(UIButton *)sender
{
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
//    [_myPlayer pause];
//    _myPlayer = nil;
//    _myMovie = nil;
    [_timer invalidate];
    _timer = nil;
    [_barTimer invalidate];
    _barTimer = nil;
    
    if (_playFlag == PlayWithURL)
    {
        for (CourseVideoModel *tempVideoModel in self.courseModel.videoList)
        {
            tempVideoModel.lastPlayTime = self.playProgressSlider.value;
            
            //将当前播放时间转化为整型再保存到模型中
            CMTime sTime = _myMovie.duration;
            sTime.value = self.playProgressSlider.value*sTime.timescale;
            
            NSInteger movieSeconds = sTime.value/sTime.timescale;
            self.courseModel.lastPlaySeconds = movieSeconds;
            self.courseModel.lastPlayPnumber = self.videoModel.pnumber;
            self.courseModel.lastPlayTime = self.playProgressSlider.value;
            NSLog(@"%f", tempVideoModel.lastPlayTime);
        }
        
        [dataManager writeToHistoryArchiverWithModel:self.courseModel];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_barTimer invalidate];
    _barTimer = nil;
    self.topView.alpha = 0;
    if (self.topView.hidden)
    {
        [[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
        [UIView animateWithDuration:0.3 animations:^{
            self.topView.hidden = NO;
            self.topView.alpha = 0.8;
            self.controlView.alpha = 0.8;
        }];
    }
    else
    {
        [[UIApplication sharedApplication]setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
        [UIView animateWithDuration:0.3 animations:^{
            self.topView.hidden = YES;
            self.topView.alpha = 0;
            self.controlView.alpha = 0;
        }];
    }
}

- (NSUInteger)supportedInterfaceOrientations
{
//    self.wantsFullScreenLayout = YES;

    return UIInterfaceOrientationMaskLandscapeRight;
    
}





@end
